﻿using Nop.Admin.Models.Common;
using Nop.Admin.Models.XJ;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.XJ;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.XJ;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
	public class EquipmentCategoryController : BaseAdminController
	{
		#region Fields
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IOrganizationService _organizationServce;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public EquipmentCategoryController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IOrganizationService organizationServce,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			ICustomerActivityService customerActivityService,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._organizationServce = organizationServce;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._customerActivityService = customerActivityService;
			this._logger = logger;
		}
		#endregion

		#region Utilities

		[NonAction]
		protected virtual void PrepareAllCategoriesModel(EquipmentCategoryModel model)
		{
			if (model == null)
				throw new ArgumentNullException("model");

			model.AvailableCategories.Add(new SelectMenuModel
			{
				name = "请选择",
				id = 0,
				open = true,
			});
			var categorys = _xJEquipmentCategoryService.GetAllCategorys(pId: 0, isConsumables: model.IsConsumables, showHidden: false);
			foreach (var c in categorys)
				model.AvailableCategories.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
		}
		#endregion


		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var model = new EquipmentCategoryListModel();

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult List(DataSourceRequest command, EquipmentCategoryListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedKendoGridJson();

			var categories = _xJEquipmentCategoryService.GetAllCategorys(
				categoryName: model.SearchCategoryName,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					var categoryModel = new EquipmentCategoryModel
					{
						Id = x.Id,
						CategoryMainId = x.CategoryMainId,
						PId = x.PId,
						Name = x.Name,
						DisplayOrder = x.DisplayOrder,
						Published = x.Published,
						Breadcrumb = x.GetFormattedBreadCrumb(_xJEquipmentCategoryService)
					};
					return categoryModel;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}

		[HttpPost]
		public virtual ActionResult Tree(int SearchPlaceId = 0, bool? isConsumables = null)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedKendoGridJson();

			var categorys = _xJEquipmentCategoryService.GetCategoryTree(xJEquipmentCategoryId: 0, placeId: SearchPlaceId, isConsumables: isConsumables);

			return Json(new List<TreeItem> { new TreeItem { id = 0, text = "全部", expanded = true, addable = true, items = categorys } });
		}
		#endregion

		#region Create / Edit / Delete

		public virtual ActionResult Create()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var model = new EquipmentCategoryModel
			{
			};
			//categories
			PrepareAllCategoriesModel(model);
			model.Published = true;

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Create(EquipmentCategoryModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var category = new XJEquipmentCategory
				{
					PId = model.PId,
					Name = model.Name,
					DisplayOrder = model.DisplayOrder,
					Published = model.Published,
				};
				_xJEquipmentCategoryService.InsertXJEquipmentCategory(category);

				//activity log
				_customerActivityService.InsertActivity("AddNewEquipmentCategory", "新增分类：{0}", category.Name);

				SuccessNotification("保存成功");

				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = category.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(id);
			if (category == null || category.Deleted)
				//No category found with the specified id
				return RedirectToAction("List");

			var model = new EquipmentCategoryModel
			{
				Id = category.Id,
				PId = category.PId,
				Name = category.Name,
				DisplayOrder = category.DisplayOrder,
				Published = category.Published
			};
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(EquipmentCategoryModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(model.Id);
			if (category == null || category.Deleted)
				//No category found with the specified id
				return RedirectToAction("List");

			if (ModelState.IsValid)
			{
				category.PId = model.PId;
				category.Name = model.Name;
				category.DisplayOrder = model.DisplayOrder;
				category.Published = model.Published;
				_xJEquipmentCategoryService.UpdateXJEquipmentCategory(category);

				//activity log
				_customerActivityService.InsertActivity("EditEquipmentCategory", "编辑分类：{0}", category.Name);

				SuccessNotification("保存成功");
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = category.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(id);
			if (category == null)
				//No category found with the specified id
				return RedirectToAction("List");

			var equipments = _xJEquipmentService.GetAllEquipments(categoryId: category.Id);
			if (equipments.Any())
			{
				ErrorNotification("不能删除");
				return RedirectToAction("List");
			}
			var subcategories = _xJEquipmentCategoryService.GetAllCategoriesByParentCategoryId(parentCategoryId: category.Id, showHidden: true);
			if (subcategories.Any())
			{
				ErrorNotification("不能删除");
				return RedirectToAction("List");
			}
			_xJEquipmentCategoryService.DeleteCategory(category);

			//activity log
			_customerActivityService.InsertActivity("DeleteEquipmentCategory", "删除分类：{0}", category.Name);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}
		#endregion

		public virtual ActionResult AddPopup(int pId, bool isConsumables = false)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var model = new EquipmentCategoryModel
			{
				PId = pId,
				DisplayOrder = 0,
				IsConsumables = isConsumables,
				Published = true,
			};
			//categories
			PrepareAllCategoriesModel(model);
			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AddPopup(string btnId, EquipmentCategoryModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var category = new XJEquipmentCategory
				{
					CategoryMainId = model.CategoryMainId,
					PId = model.PId,
					Name = model.Name,
					DisplayOrder = model.DisplayOrder,
					IsConsumables = model.IsConsumables,
					Published = model.Published,
				};
				_xJEquipmentCategoryService.InsertXJEquipmentCategory(category);
				model.Id = category.Id;
				//activity log
				_customerActivityService.InsertActivity("AddNewEquipmentCategory", "新增分类：{0}", category.Name);
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			return View(model);
		}

		public virtual ActionResult EditPopup(int id, bool isConsumables = false)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var model = new EquipmentCategoryModel();
			var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(id);
			if (category != null)
			{
				model.CategoryMainId = category.CategoryMainId;
				model.Id = category.Id;
				model.PId = category.PId;
				model.Name = category.Name;
				model.DisplayOrder = category.DisplayOrder;
				model.IsConsumables = isConsumables;
				model.Published = category.Published;
			}
			//categories
			PrepareAllCategoriesModel(model);
			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult EditPopup(string btnId, EquipmentCategoryModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				if (model.Id > 0)
				{
					var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(model.Id);
					if (null != category)
					{
						category.PId = model.PId;
						category.Name = model.Name;
						_xJEquipmentCategoryService.UpdateXJEquipmentCategory(category);

						//activity log
						_customerActivityService.InsertActivity("EditEquipmentCategory", "编辑分类：{0}", category.Name);
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult CategoryDelete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageEquipments))
				return AccessDeniedView();

			var category = _xJEquipmentCategoryService.GetXJEquipmentCategoryById(id);
			if (category != null)
			{
				var equipments = _xJEquipmentService.GetAllEquipments(categoryId: category.Id);
				if (!equipments.Any())
				{
					var subcategories = _xJEquipmentCategoryService.GetAllCategoriesByParentCategoryId(parentCategoryId: category.Id, showHidden: true);
					if (!subcategories.Any())
					{
						_xJEquipmentCategoryService.DeleteCategory(category);

						//activity log
						_customerActivityService.InsertActivity("DeleteEquipmentCategory", "删除分类：{0}", category.Name);
						return Json(new { result = true });
					}
				}
			}

			return Json(new { result = false });
		}
	}
}